import requests
from contextlib import closing


def download_image_improved():
    """demo: 下载图片
    """
    # 伪造headers信息
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36'}
    # 限定url
    url = "http://img01.tooopen.com/Downs/images/2011/7/27/sy_20110727222501209015.jpg"
    response = requests.get(url, headers=headers, stream=True)
    # with closing(requests.get(url, headers=headers, stream=True)) as response:
    #     # 打开文件
    #     with open('images/demo1.jpg', 'wb') as fd:
    #         # 每128写入一次
    #         for chunk in response.iter_content(128):
    #             fd.write(chunk)
    i = 2
    with closing(requests.get(url, headers=headers, stream=True)) as response:
        with open('images/demo' + str(i) + '.jpg', 'wb') as fd:
            for chunk in response.iter_content(128):
                fd.write(chunk)


download_image_improved()
